// @flow
import React from 'react'
import { Tabs, Table, DatePicker, Select, Spin, message, Checkbox } from 'antd'
import DynamicLine from 'components/DynamicLine'
import ScatterHistoryLine from 'components/ScatterHistoryLine'
import moment from 'moment'
import SelectIndicator from 'components/SelectIndicator'
import HistoryDataGrid from 'components/HistoryDataGrid'
import DynamicFre from 'components/DynamicFre'
import DynamicDirec from 'components/DynamicDirec'
import HistoryFre from 'components/HistoryFre'
import HistoryDirec from 'components/HistoryDirec'
import { changeHistoryChartCond,
  changeDynamicChartCond, changeDynamicDateCond } from 'store/modules/deviceFileCondition'
import styles from './Condition.css'
import classname from 'classnames/bind'
import { connect } from 'react-redux'
import universalFetch, { handleFetchError, LoginFetch } from 'store/modules/fetch'
import HistoryLine from 'components/HistoryLine'
import HistoryLineMore from 'components/HistoryLineMore' // 为加点击显示值从historyLine重新分离
import Bode from 'components/Bode'
import R from 'ramda'
const TabPane = Tabs.TabPane
const Option = Select.Option
const { RangePicker } = DatePicker
const cx = classname.bind(styles)
const columns = [
  { title: '事件名称',
    dataIndex: 'eventName' },
  { title: '事件类型',
    dataIndex: 'eventType'
  },
  { title: '测点名称',
    dataIndex: 'checkName'
  },
  { title: '开始时间',
    dataIndex: 'startTime'
  },
  { title: '结束时间',
    dataIndex: 'endTime'
  },
  { title: '负责人',
    dataIndex: 'owner'
  },
  { title: '处理状态',
    dataIndex: 'status'
  },
  { title: '事件描述',
    dataIndex: 'detail'
  }
]

type Props = {
  deviceCard: Object,
  location: Object,
  history: Object,
  deviceFileCondition: Object,
  changeHistoryChartCond: Function,
  changeDynamicChartCond: Function,
  changeDynamicDateCond: Function
}

type State = {
  chartData: Array<any>,
  tableData: Array<any>, // 表格展示所用的数据
  tableCheck: boolean, // 表格展示 是否选中原始波形
  dynamicTable: Array<any>,
  historyTable: Array<any>,
  historyFrom: any,
  historyTo: any,
  xData: Array<any>,
  dynamicIndicator: Array<string>,
  defaultChannel: Array<string>,
  groupId: string,
  deviceData: Object,
  historyDates: Array<moment>, // 时间显示
  dynamicDates: Array<moment>,
  historyDataTime: string, // 快捷时间
  chartView: string,
  dynamicChartView: string,
  dynamicChartViewNow: boolean, // 保证每次点击动态数据单图时，可以重新加载
  scatterData: Array<Object>,
  scatterXLabel: string,
  defaultActiveKey: string,
  loading: boolean,
  changeXData: Array<string>,
  IndicatorEmpty: boolean,
  dataType: string,
  datatypeDict: Array<Object>
}

class Condition extends React.Component {
  props: Props
  state: State
  refreshHistoryChartData: Function
  refreshDyncValueTableData: Function
  updataTable: Function
  historyTable: Function
  plotBands: Function
  columns1: Array<Object>
  changeHistoryCond: Function
  changeDynamicCond: Function
  historyTimeCondOnOk: Function
  changeHistoryTimeCond: Function
  changeDynamicDate: Function
  dynamicDateCondOnOk: Function
  changeChartView: Function
  changeDynamicChartView: Function
  changeScatter: Function
  initialDraw: Function
  tabOnchange: Function
  changeDatatype: Function
  changeDataTime: Function
  getDatatype: Function
  showDyncValue: Function
  constructor (props: Object) {
    super(props)
    const component = this
    this.columns1 = [
      { title: '事件名称',
        dataIndex: 'eventName',
        render: (text, record, index) => (
          <a onClick={
            function () {
              component.plotBands(record)
            }}>
            {text}
          </a>
        )
      },
      { title: '事件类型',
        dataIndex: 'eventType'
      },
      { title: '测点名称',
        dataIndex: 'checkName'
      },
      { title: '开始时间',
        dataIndex: 'startTime'
      },
      { title: '结束时间',
        dataIndex: 'endTime'
      },
      { title: '负责人',
        dataIndex: 'owner'
      },
      { title: '处理状态',
        dataIndex: 'status'
      },
      { title: '事件描述',
        dataIndex: 'detail'
      }
    ]

    this.state = {
      chartData: [],
      tableData: [],
      tableCheck: false,
      dynamicTable: [],
      historyTable: [],
      xData: [],
      dynamicIndicator: [''],
      defaultChannel: [''],
      groupId: this.props.deviceCard.groupId,
      historyFrom: null,
      historyTo: null,
      deviceData: this.props.deviceCard.deviceData,
      historyDates: [moment(0, 'HH'), moment()],
      dynamicDates: [],
      historyDataTime: '快捷时间',
      scatterData: [],
      chartView: 'single',
      dynamicChartView: 'Dsingle',
      dynamicChartViewNow: false,
      scatterXLabel: 'time',
      defaultActiveKey: 'dynamicTab',
      loading: false,
      changeXData: [],
      IndicatorEmpty: false,
      dataType: '1',
      datatypeDict: []
    }

    this.refreshHistoryChartData = this.refreshHistoryChartData.bind(this)
    this.refreshDyncValueTableData = this.refreshDyncValueTableData.bind(this)
    this.updataTable = this.updataTable.bind(this)
    this.historyTable = this.historyTable.bind(this)
    this.plotBands = this.plotBands.bind(this)
    this.changeHistoryCond = this.changeHistoryCond.bind(this)
    this.changeDynamicCond = this.changeDynamicCond.bind(this)
    this.historyTimeCondOnOk = this.historyTimeCondOnOk.bind(this)
    this.changeHistoryTimeCond = this.changeHistoryTimeCond.bind(this)
    this.changeDynamicDate = this.changeDynamicDate.bind(this)
    this.dynamicDateCondOnOk = this.dynamicDateCondOnOk.bind(this)
    this.changeChartView = this.changeChartView.bind(this)
    this.changeDynamicChartView = this.changeDynamicChartView.bind(this)
    this.changeScatter = this.changeScatter.bind(this)
    this.initialDraw = this.initialDraw.bind(this)
    this.tabOnchange = this.tabOnchange.bind(this)
    this.changeDatatype = this.changeDatatype.bind(this)
    this.changeDataTime = this.changeDataTime.bind(this)
    this.getDatatype = this.getDatatype.bind(this)
    this.showDyncValue = this.showDyncValue.bind(this)
  }

  componentWillMount () {
    const state = this.props.location.state
    const compoment = this
    if (state) {
      // 默认展示的tab key
      if (state.hasOwnProperty('defaultActiveKey')) {
        this.setState({
          defaultActiveKey: state.defaultActiveKey
        })
      }
      // 默认选中的指标变量
      if (state.hasOwnProperty('dynamicIndicator')) {
        let Ind = []
        Ind.push(state.dynamicIndicator)
        this.setState({
          dynamicIndicator: Ind
        })
        if (state.dynamicIndicator === '') {
          this.setState({
            IndicatorEmpty: true
          })
        }
      }
      // 默认选中的指标通道
      if (state.hasOwnProperty('defaultChannel')) {
        this.setState({
          defaultChannel: state.defaultChannel
        })
      }
      // 默认显示的时间
      if (state.hasOwnProperty('startTime')) {
        this.setState({
          historyDates: [moment(state.startTime), moment(state.endTime)]
        }, () => {
          // 将url中传值的时间传到store中
          const { historyCond } = compoment.props.deviceFileCondition
          compoment.props.changeHistoryChartCond(Object.assign({}, historyCond, {
            startTime: moment(state.startTime),
            endTime: moment(state.endTime)
          }))
        })
      }
    }
    // 将历史的默认时间传到store中
    const { historyCond } = this.props.deviceFileCondition
    this.props.changeHistoryChartCond(Object.assign({}, historyCond, {
      monitors: [],
      keyNameValue: '',
      startTime: this.state.historyDates[0],
      endTime: this.state.historyDates[1]
    }))
    // 历史数据中的数据类型列表
    this.getDatatype()
    // 请求table数据
    this.historyTable()
  }

  componentWillReceiveProps (nextProps) {
    const { defaultActiveKey } = this.state
    this.historyTable()
    if (defaultActiveKey === 'historyTab') {
      this.initialDraw(nextProps)
    }
  }

  changeChartView (value) {
    this.setState({
      chartView: value
    })
    // 多图每图联动加线后会删除前面的数据，重新加载解决这个问题
    if (value === 'single' || value === 'more') {
      this.initialDraw(this.props)
    }
  }
  changeDynamicChartView (value) {
    this.setState({
      dynamicChartView: value,
      dynamicChartViewNow: true
    })
  }
  getDatatype () {
    // 从字典中取得datatype的值
    universalFetch(`${__SERVICE_API__}sys/dicts?pageNum=1&pageSize=200&type=datatype`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }

        this.setState({
          datatypeDict: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  // 改变dataType的值
  changeDatatype (value) {
    const compoment = this
    this.setState({
      loading: true,
      dataType: value
    }, () => {
      compoment.initialDraw(compoment.props)
    })
  }
  // 快捷改变数据的时间段
  changeDataTime (value) {
    let historyDates
    if (value === '8h') {
      historyDates = [moment().subtract(8, 'h'), moment()]
    } else {
      historyDates = [moment().subtract(1, value), moment()]
    }
    this.setState({
      historyDataTime: value, // 快捷显示时间
      historyDates: historyDates // 时间显示
    })
    const { historyCond } = this.props.deviceFileCondition
    this.props.changeHistoryChartCond(Object.assign({}, historyCond, {
      startTime: historyDates[0],
      endTime: historyDates[1]
    }))
    const components = this
    setTimeout(() => {
      components.historyTable()
    }, 100)
  }
/**
 * 历史表格数据&&历史表格
 * @return {[type]} [description]
 */
  historyTable () {
    const { historyCond } = this.props.deviceFileCondition
    const { startTime, endTime } = historyCond
    universalFetch(`${__SERVICE_API__}device/devices/${this.state.deviceData.id}/events?orderBy=update_time%20desc` +
      `&startDate=${startTime.toISOString()}&endDate=${endTime.toISOString()}`
    )
    // universalFetch(`${__SERVICE_API__}device/devices/${this.state.deviceData.id}/events?orderBy=update_time%20desc`)
      .then((res) => res.json())
      .then((json) => {
        const result = json.result.eventList
        this.setState({
          historyTable:result.map((data, i) => {
            data['startTime'] = moment(data.startTime, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format('YYYY-MM-DD HH:mm:ss')
            data['endTime'] = moment(data.endTime, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format('YYYY-MM-DD HH:mm:ss')
            data['key'] = i
            return data
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  /**
   * 历史折线数据
   * @return {[type]} [description]
   */
  refreshHistoryChartData (monitors, keyNameValue, start, end) {
    this.setState({
      loading: true
    })
    const deviceNo = this.state.deviceData.deviceNo.split('_')
    let channelNames = []
    const res = monitors.map((monitorsItem, i) => {
      channelNames = monitorsItem.channelNames
      let postBody = {
        fieldGroup: monitorsItem.En,
        fields: monitorsItem.key,
        coValueFilter: {
          idFieldFilter: {
            factory_id: { '$eq': String(deviceNo[0]) },
            equipment_id: { '$eq': String(deviceNo[1]) },
            machine_id: { '$eq': String(deviceNo[2]) },
            datatype: { '$eq': this.state.dataType },
            '$or': monitorsItem.channelIds.map((d, i) => {
              return { 'channel_id': { '$eq': String(d) } }
            })
          }
        },
        timeRange: {
          start: start,
          end: end
        },
        valueFilters: [
            { '$default': { '$or': [{ '$gt': -1000000 }] } }
        ],
        size: 10000,
        page: 1
      }
      if (monitorsItem.En === 'c_sta') { // 如果是过程量就请求channel_type = 1 的值
        postBody.coValueFilter.idFieldFilter['channel_type'] = { '$eq': '1' }
      }
      return LoginFetch(`${__KMX_API__}data-streams`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(postBody)
      }).then((res) => res.json())
    })
    Promise.all(res).then((jsons) => {
      let results = []
      jsons.map((d) => {
        if (d.code === 1) {
          message.error('请求数据失败: ' + d.message)
          this.setState({
            chartData: []
          })
          return
        }
        results.push(...d.results)
      })
      this.setState({
        loading: false
      })
      let monitorNames = []
      monitors.map((d) => {
        monitorNames.push(...d.keyName)
      })
      const cloneResults = R.clone(results)
      if (results && results.length > 0) {
        const chartData = results.map((data, index) => {
          const channelArray = channelNames.filter((dd) => dd.id === data.compoundId.channel_id)
          const name = monitorNames.filter((dd) => dd.key === data.field)[0].name
          const monitIndex = monitors.filter((dd) => dd.key.indexOf(data.field) > -1)
          data['name'] = name + '__' + channelArray[0].name
          data['type'] = 'line'
          data['data'] = data.streams.map((d, i) => {
            return d
          })
          data['sensorNameEn'] = monitIndex[0].En // 用于底部事件名称点击绘图
          data['sensorName'] = monitIndex[0].sensorType // 用于底部事件名称点击绘图
          return data
        })
        this.setState({
          chartData: chartData,
          tableData: chartData,
          tableCheck: false,
          scatterData: cloneResults.map((data, index) => {
            const channelArray = channelNames.filter((dd) => dd.id === data.compoundId.channel_id)
            const name = monitorNames.filter((dd) => dd.key === data.field)[0].name
            const monitIndex = monitors.filter((dd) => dd.key.indexOf(data.field) > -1)
            data['name'] = name + '__' + channelArray[0].name
            data['type'] = 'scatter'
            data['data'] = data.streams.map((d, i) => {
              return d
            })
            data['sensorNameEn'] = monitIndex[0].En // 用于底部事件名称点击绘图
            data['sensorName'] = monitIndex[0].sensorType // 用于底部事件名称点击绘图
            return data
          }),
          changeXData: cloneResults.map((data, index) => {
            const channelArray = channelNames.filter((dd) => dd.id === data.compoundId.channel_id)
            const name = monitorNames.filter((dd) => dd.key === data.field)[0].name
            return name + '__' + channelArray[0].name
          }),
          xData: results[0].streams.map((d, i) => {
            return d[0]
          })
        })
      }
    })
    .catch(() => {
      this.setState({
        loading: false
      })
    })
  }

  /**
   * 表格展示数据（写这函数主要为展示表格数据的动态波形）
   * @return {[type]} [description]
   */
  refreshDyncValueTableData (monitors, keyNameValue, start, end) {
    this.setState({
      loading: true
    })
    const deviceNo = this.state.deviceData.deviceNo.split('_')
    let channelNames = []
    const res = monitors.map((monitorsItem, i) => {
      channelNames = monitorsItem.channelNames
      let postBody = {
        fieldGroup: monitorsItem.En,
        fields: monitorsItem.key,
        coValueFilter: {
          idFieldFilter: {
            factory_id: { '$eq': String(deviceNo[0]) },
            equipment_id: { '$eq': String(deviceNo[1]) },
            machine_id: { '$eq': String(deviceNo[2]) },
            datatype: { '$eq': this.state.dataType },
            '$or': monitorsItem.channelIds.map((d, i) => {
              return { 'channel_id': { '$eq': String(d) } }
            })
          }
        },
        timeRange: {
          start: start,
          end: end
        },
        size: 10000,
        page: 1
      }
      if (monitorsItem.En === 'c_sta') { // 如果是过程量就请求channel_type = 1 的值
        postBody.coValueFilter.idFieldFilter['channel_type'] = { '$eq': '1' }
      }
      return LoginFetch(`${__KMX_API__}data-streams`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(postBody)
      }).then((res) => res.json())
    })
    Promise.all(res).then((jsons) => {
      let results = []
      jsons.map((d) => {
        if (d.code === 1) {
          message.error('请求数据失败: ' + d.message)
          this.setState({
            tableData: []
          })
          return
        }
        results.push(...d.results)
      })
      this.setState({
        loading: false
      })
      let monitorNames = []
      monitors.map((d) => {
        monitorNames.push(...d.keyName)
      })
      if (results && results.length > 0) {
        this.setState({
          tableData: results.map((data, index) => {
            const channelArray = channelNames.filter((dd) => dd.id === data.compoundId.channel_id)
            const name = monitorNames.filter((dd) => dd.key === data.field)[0].name
            const monitIndex = monitors.filter((dd) => dd.key.indexOf(data.field) > -1)
            data['name'] = name + '__' + channelArray[0].name
            data['type'] = 'line'
            data['data'] = data.streams.map((d, i) => {
              return d
            })
            data['sensorNameEn'] = monitIndex[0].En // 用于底部事件名称点击绘图
            data['sensorName'] = monitIndex[0].sensorType // 用于底部事件名称点击绘图
            return data
          })
        })
      }
    })
    .catch(() => {
      this.setState({
        loading: false
      })
    })
  }

  changeScatter (xlabel) {
    this.setState({
      scatterXLabel: xlabel
    })
    // const { scatterData } = this.state
  }

  updataTable () {
    this.historyTable()
  }

  // 选中某段日期
  plotBands (record) {
    // 需求修改，选中某段日期改为显示该测点该事件的历史数据
    // this.setState({
    //   historyFrom: moment(record.startTime).valueOf(),
    //   historyTo: moment(record.endTime).valueOf()
    // })
    this.setState({
      loading: true
    })
    const monitors = [{
      En: record.sensorNameEn,
      sensorType: record.sensorName,
      key: [record.variableNameEn],
      channelIds: [String(record.channelId)],
      channelNames: [
        {
          id: String(record.channelId),
          name: record.checkName.split('__')[1]
        }
      ],
      keyName: [
        {
          key: record.variableNameEn,
          name: record.checkName.split('__')[0]
        }
      ]
    }]
    const keyNameValue = ''
    const startTime = record.startTime
    const endTime = record.endTime
    // 不改变历史数据选择条件的存值，直接执行画图函数
    // this.refreshHistoryChartData(
    //  monitors,
    //  keyNameValue,
    //  moment(startTime).format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
    //  moment(endTime).format('YYYY-MM-DDTHH:mm:ss.SSSZ')
    // )
    // 改变历史数据选择条件的存值，然后刷新执行执行画图函数
    const { historyCond } = this.props.deviceFileCondition
    this.props.changeHistoryChartCond(Object.assign({}, historyCond, {
      monitors: monitors,
      keyNameValue: keyNameValue,
      startTime: moment(startTime),
      endTime: moment(endTime)
    }))
    // 改变页面上的显示值
    const int = record.sensorNameEn + '___' + record.variableNameEn
    const channel = [record.channelId + '__' + record.checkName.split('__')[1]]
    this.setState({
      historyDates: [moment(startTime), moment(endTime)], // 时间显示
      dynamicIndicator: [int], // 指标显示
      defaultChannel: channel
    })
    // const { deviceCard, history } = this.props
    // const location1 = {
    //   pathname:`/device-file/${deviceCard.id}/condition`,
    //   state: {
    //     defaultActiveKey: 'historyTab',
    //     dynamicIndicator: int,
          // defaultChannel: channel
    //     startTime: startTime,
    //     endTime: endTime
    //   }
    // }
    // history.push(location1)
  }

  /**
   * 改变历史图表选择指标条件
   * @param  {[type]} monitors [description]
   * @return {[type]}          [description]
   */
  changeHistoryCond (monitors, keyNameValue) {
    this.setState({
      loading: true
    })
    const { historyCond } = this.props.deviceFileCondition
    this.props.changeHistoryChartCond(Object.assign({}, historyCond, {
      monitors: monitors,
      keyNameValue: keyNameValue
    }))
  }

  changeDynamicCond (monitors, keyNameValue) {
    // this.props.changeDynamicChartCond(monitors)
    this.props.changeDynamicChartCond({
      monitors: monitors,
      keyNameValue: keyNameValue
    })
  }

  /**
    * 改变历史图表时间选择条件
    * @return {[type]} [description]
    */
  changeHistoryTimeCond (dates, dateStrings) {
    this.setState({
      historyDates: dates,
      historyDataTime: '快捷时间'
    })
  }

   /**
    * 历史时间条件点击确定回调
    * @return {[type]} [description]
    */
  historyTimeCondOnOk () {
    const { historyCond } = this.props.deviceFileCondition
    this.props.changeHistoryChartCond(Object.assign({}, historyCond, {
      startTime: this.state.historyDates[0],
      endTime: this.state.historyDates[1]
    }))
    const components = this
    setTimeout(() => {
      components.historyTable()
    }, 100)
  }

  initialDraw (props) {
    const { historyCond } = props.deviceFileCondition
    if (historyCond && historyCond.monitors && historyCond.monitors.length === 0) {
      return
    }

    // let monitorNames = []
    // historyCond.monitors.map((d) => {
    //   monitorNames.push(...d.keyName)
    // })
    // this.setState({
    //   chartData: monitorNames.map((data, index) => {
    //     return {
    //       name: data,
    //       type: 'line',
    //       data: []
    //     }
    //   })
    // })

    this.refreshHistoryChartData(
     historyCond.monitors,
     historyCond.keyNameValue,
     historyCond.startTime.format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
     historyCond.endTime.format('YYYY-MM-DDTHH:mm:ss.SSSZ')
    )
  }

  changeDynamicDate (dates) {
    this.setState({
      dynamicDates: dates
    })
  }

  dynamicDateCondOnOk () {
    const { dynamicDate } = this.props.deviceFileCondition
    this.props.changeDynamicDateCond(Object.assign({}, dynamicDate, {
      startTime: this.state.dynamicDates[0],
      endTime: this.state.dynamicDates[1]
    }))
  }
  tabOnchange (activeKey) {
    this.setState({
      defaultActiveKey: activeKey
    })
  }

  showDyncValue (e) {
    const checked = e.target.checked
    this.setState({
      tableCheck: checked
    })
    const { historyCond } = this.props.deviceFileCondition
    if (historyCond && historyCond.monitors && historyCond.monitors.length === 0) {
      return
    }
    if (checked) {
      let flag = false // 判断是否选中了振动量
      const monitors = R.clone(historyCond.monitors).map((d, i) => {
        if (d.En === 'c_vib') {
          flag = true
          if (d.key.indexOf('dyna_value') === -1) {
            d.key.push('dyna_value')
            d.keyName.push({ key: 'dyna_value', name: '原始波形' })
          }
        }
        return d
      })
      if (flag) {
        this.refreshDyncValueTableData(
         monitors,
         historyCond.keyNameValue,
         historyCond.startTime.format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
         historyCond.endTime.format('YYYY-MM-DDTHH:mm:ss.SSSZ')
        )
      }
    } else {
      this.setState({
        tableData: this.state.chartData
      })
    }
  }

  render () {
    // const { historyCond, dynamicDate } = this.props.deviceFileCondition
    const { datatypeDict, chartData, chartView, dynamicChartView, scatterXLabel, loading, changeXData } = this.state
    const chartDataLen = chartData.length
    const scatterSettingStyle = cx({
      'scatter-settings': true,
      'animated': true,
      'fadeInRight': chartView === 'scatter',
      // 'fadeInLeft': chartView !== 'scatter',
      'scatter-hide': chartView !== 'scatter'
    })
    const { keyName } = this.state.deviceData
    // let monitorKeys = []
    // historyCond.monitors.map((d) => {
    //   monitorKeys.push(...d.key)
    // })
    let dyncValue = 'none' // 表格展示原始波形是否可见
    if (this.props.deviceCard.deviceData.dataSource === 'S8000') {
      dyncValue = 'inline-block'
    }
    return (
      <div className={styles['main']}>
        <Tabs type='card' defaultActiveKey={this.state.defaultActiveKey} onChange={this.tabOnchange} >
          <TabPane tab='实时数据' key='dynamicTab'>
            <div>
              {
              // <Select defaultValue='单图显示' style={{ width: 120, marginLeft:8 }}>
              //   <Option value='单图显示'>单图显示</Option>
              //   <Option value='多图显示'>多图显示</Option>
              //   <Option value='散点显示'>散点显示</Option>
              // </Select>
              // <RangePicker
              //   showTime
              //   format='YYYY-MM-DD HH:mm:ss'
              //   defaultValue={[dynamicDate.startTime, dynamicDate.endTime]}
              //   onOk={() => this.dynamicDateCondOnOk()}
              //   onChange={this.changeDynamicDate}
              //   style={{ marginLeft: 8 }}
              // />
              }
              <Select defaultValue='Dsingle'
                style={{ width: 80 }}
                onChange={this.changeDynamicChartView}
                >
                <Option value='Dsingle'>单图显示</Option>
                <Option value='dynamicFre'>一倍频</Option>
                <Option value='dynamicDeric'>通频转速</Option>
              </Select>
              <SelectIndicator
                dynamicIndicator={this.state.dynamicIndicator}
                defaultChannel={this.state.defaultChannel}
                keyName={keyName.split(',')}
                IndicatorEmpty={this.state.IndicatorEmpty}
                callback={this.changeDynamicCond}
                />
            </div>
            {
              dynamicChartView === 'Dsingle'
              ? <div className={styles['top']}>
                <DynamicLine
                  dynamicIndicator={this.state.dynamicIndicator}
                  // 为了切换单图时重新加载DynamicLine组件
                  dynamicChartViewNow={this.state.dynamicChartViewNow}
                  historyFrom={this.state.historyFrom}
                  historyTo={this.state.historyTo}
                  updateEvents={this.updataTable}
                  />
              </div>
              : false
            }
            {
              dynamicChartView === 'dynamicFre'
              ? <div className={styles['top']}>
                <DynamicFre {...{
                  deviceData: this.props.deviceCard.deviceData
                }} />
              </div>
              : false
            }
            {
              dynamicChartView === 'dynamicDeric'
              ? <div className={styles['top']}>
                <DynamicDirec {...{
                  deviceData: this.props.deviceCard.deviceData
                }} />
              </div>
              : false
            }
            <Table
              className={styles['table']}
              dataSource={this.state.historyTable}
              columns={columns}
              size='small'
              bordered />
          </TabPane>
          <TabPane tab='历史数据' key='historyTab'>
            <div>
              <Select defaultValue='single'
                style={{ width: 80 }}
                onChange={this.changeChartView}
                >
                <Option value='single'>单图显示</Option>
                {
                  chartDataLen > 1
                  ? <Option value='more'>多图显示</Option>
                  : <Option value='more' disabled>多图显示</Option>
                }
                <Option value='scatter'>散点显示</Option>
                <Option value='table'>表格显示</Option>
                <Option value='historyFre'>一倍频</Option>
                <Option value='historyDeric'>通频转速</Option>
              </Select>
              {
                chartView === 'historyFre' || chartView === 'historyDeric'
                ? ''
                : <label>
                  <RangePicker
                    showTime
                    format='YYYY-MM-DD HH:mm:ss'
                    // defaultValue={[historyCond.startTime, historyCond.endTime]}
                    value={this.state.historyDates}
                    onOk={() => this.historyTimeCondOnOk()}
                    onChange={this.changeHistoryTimeCond}
                    style={{ marginLeft: 8 }}
                    />
                  <Select defaultValue='当前数据'
                    style={{ marginLeft: 8 }}
                    placeholder='数据类型'
                    onChange={this.changeDatatype}
                    >
                    {
                      datatypeDict.map((d, i) => {
                        return <Option key={i} value={d.value}>{d.label}</Option>
                      })
                    }
                  </Select>
                  <Select
                    style={{ marginLeft: 8, width: 80 }}
                    placeholder='快捷时间'
                    value={this.state.historyDataTime}
                    onChange={this.changeDataTime}
                    >
                    <Option value='h'>一小时</Option>
                    <Option value='8h'>八小时</Option>
                    <Option value='d'>一天</Option>
                    <Option value='w'>一周</Option>
                    <Option value='M'>一月</Option>
                    <Option value='y'>一年</Option>
                  </Select>
                  <SelectIndicator
                    dynamicIndicator={this.state.dynamicIndicator}
                    defaultChannel={this.state.defaultChannel}
                    keyName={keyName.split(',')}
                    IndicatorEmpty={this.state.IndicatorEmpty}
                    callback={this.changeHistoryCond}
                  />
                  {
                    chartView === 'table'
                    ? <Checkbox
                      checked={this.state.tableCheck}
                      onChange={this.showDyncValue}
                      disabled={loading}
                      style={{ marginLeft: 20, display: dyncValue }}>显示原始波形数据</Checkbox>
                    : ''
                  }
                </label>
              }
              <div className={scatterSettingStyle}>
                <span className={styles['scatter-label']}>切换为横轴的点:</span>
                <Select
                  showSearch
                  filterOption={(input, option) => {
                    return option.props.children.indexOf(input) >= 0
                  }}
                  style={{ width: 120 }}
                  defaultValue='time'
                  onChange={this.changeScatter}
                  >
                  <Option value='time'>
                    时间
                  </Option>
                  {
                    changeXData.length > 1
                    ? changeXData.map((item, i) => {
                      return <Option key={i} value={item}>
                        {item}
                      </Option>
                    })
                    : []
                  }
                </Select>
              </div>
            </div>
            {
              chartView === 'single'
              ? <div className={styles['top']}>
                <Spin spinning={loading} tip='加载中...'>
                  <HistoryLine
                    xData={this.state.xData}
                    chartData={this.state.chartData}
                    historyFrom={this.state.historyFrom}
                    historyTo={this.state.historyTo}
                    updateEvents={this.updataTable}
                  />
                </Spin>
              </div>
              : false
            }
            {
              chartView === 'more'
              ? <div className={styles['multi-chart']}>
                {
                  chartData.map((item, i) => {
                    return <div key={i} className={styles['chart-item']}>
                      <Spin spinning={loading} tip='加载中...'>
                        <HistoryLineMore
                          chartData={[item]}
                          historyFrom={this.state.historyFrom}
                          historyTo={this.state.historyTo}
                          updateEvents={this.updataTable}
                        />
                      </Spin>
                    </div>
                  })
                }
              </div>
              : false
            }
            {
              chartView === 'scatter' && scatterXLabel === 'time'
              ? <div className={styles['scatter-chart']}>
                <Spin spinning={loading} tip='加载中...'>
                  <HistoryLine
                    type='scatter'
                    chartData={this.state.scatterData}
                    historyFrom={this.state.historyFrom}
                    historyTo={this.state.historyTo}
                    updateEvents={this.updataTable}
                  />
                </Spin>
              </div>
              : false
            }

            {
              chartView === 'scatter' && scatterXLabel !== 'time'
              ? <div className={styles['scatter-chart']}>
                <Spin spinning={loading} tip='加载中...'>
                  <ScatterHistoryLine
                    {...{
                      field: scatterXLabel,
                      chartData: this.state.scatterData
                    }}
                  />
                </Spin>
              </div>
              : false
            }
            {
              chartView === 'table'
              ? <div className={styles['scatter-chart']}>
                <Spin spinning={loading} tip='加载中...'>
                  <HistoryDataGrid
                    {...{
                      rowData: this.state.tableData
                    }}
                  />
                </Spin>
              </div>
              : false
            }
            {
              chartView === 'historyFre'
              ? <div className={styles['top']}>
                <HistoryFre {...{
                  historyCond: this.props.deviceFileCondition.historyCond,
                  deviceData: this.props.deviceCard.deviceData,
                  datatypeDict: datatypeDict
                }} />
              </div>
              : false
            }
            {
              chartView === 'historyDeric'
              ? <div className={styles['top']}>
                <HistoryDirec {...{
                  historyCond: this.props.deviceFileCondition.historyCond,
                  deviceData: this.props.deviceCard.deviceData,
                  datatypeDict: datatypeDict
                }} />
              </div>
              : false
            }
            <Table
              className={styles['table']}
              dataSource={this.state.historyTable}
              columns={this.columns1}
              size='small'
              bordered />
          </TabPane>
          <TabPane tab='伯德图' key='bodeTab'>
            <Bode {...{
              historyCond: this.props.deviceFileCondition.historyCond,
              deviceData: this.props.deviceCard.deviceData
            }} />
          </TabPane>
        </Tabs>
      </div>
    )
  }
 }

const mapStatesToProps = (state) => {
  return {
    deviceCard: state.deviceCard,
    deviceFileCondition: state.deviceFileCondition
  }
}
export default connect(mapStatesToProps, {
  changeHistoryChartCond, changeDynamicChartCond, changeDynamicDateCond })(Condition)
